package com.xinnet.mms.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;


/**
 * JSON转换工具
 * 
 * @author sean feng
 * @日期 2014-2-25
 */
public class JsonUtil {
	private static ObjectMapper objectMapper = new ObjectMapper();

	public static Map<String, String> toMap(String strJson) {
		Map<String, String> tmp = new HashMap<String, String>();
		try {
			Map<?, ?> map = objectMapper.readValue(strJson, Map.class);
			Iterator<?> iter = map.entrySet().iterator();
			while (iter.hasNext()) {
				Entry<?, ?> entry = (Entry<?, ?>) iter.next();
				if (entry.getValue() instanceof String) {
					tmp.put((String) entry.getKey(), (String) entry.getValue());
				}
			}
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return tmp;
	}

	public static List<String> toList(String strJson) {
		List<String> tmp = new ArrayList<String>();
		try {
			List<?> ls = objectMapper.readValue(strJson, List.class);
			if (ls != null) {
				for (Object o : ls) {
					tmp.add(objectMapper.writeValueAsString(o));
				}
			}
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return tmp;
	}

	public static <T> T toBean(String strJson, Class<T> clazz) {
		T t = null;
		try {
			t = objectMapper.readValue(strJson, clazz);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return t;
	}
	
	public static String toJson(Object object) {
		String str = null;
		try {
			str = objectMapper.writeValueAsString(object);
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str;
	}

}
